import datetime
import time

from django.shortcuts import render
from rest_framework import viewsets
from django.db.models import Q, F
from django.db.models import Count
from medias.models import MediaContent, ContentType, Image, AccountBindMediaContent, Label
from platefrom.models import Skus, Platefrom, SkusUser
from user.models import User, UserAccountBind
from medias.serializers import MediasSerializer, \
    ImageSerializer, AccountBindMediaContentSerializer, \
    VideoSerializer, ContentTypeSerializer, LabelSerializer
from rest_framework.decorators import action
from medias.filter import MediasFilter, ImageFilter
from utils.response_util import VueAPIResponse, APIResponse
from utils.pagination_util import PageNumberPaginationUtil
from .serializers import MediasSerializer
from django.conf import settings
from server.utils import check_group_id
from rest_framework.response import Response
from rest_framework import status as response_status
from django.utils.decorators import method_decorator
from rest_framework.decorators import permission_classes
from django.views.decorators.csrf import csrf_exempt

# manager
from server.urls import manager
from ez_android_automator.bilibili_task import BilibiliPublishVideoTask, bilibili_file_pkg, BilibiliPhoneLoginTask
from ez_android_automator.xhs_task import XhsPhoneLoginTask, XhsPublishVideoTask, xhs_file_pkg
from ez_android_automator.douyinhuoshan_task import DouyinhuoshanPhoneLoginTask, DouyinhuoshanPublishVideoTask, \
    douyinhuoshan_file_pkg
from ez_android_automator.weibo_task import WeiboPhoneLoginTask, WeiboPublishVideoTask, weibo_file_pkg
from ez_android_automator.toutiao_task import ToutiaoPhoneLoginTask, ToutiaoPublishVideoTask, toutiao_file_pkg
from ez_android_automator.kuaishou_task import KuaishouPhoneLoginTask, KuaishouPublishVideoTask, kuaishou_file_pkg
from ez_android_automator.client import CombinedSequentialTask
from ez_android_automator.app_file import PullAccountTask, PushAccountTask


class MediasListView(viewsets.ModelViewSet):
    queryset = MediaContent.objects.all()
    serializer_class = MediasSerializer
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        user_group_id = self.request.user.group_id
        if check_group_id(user_group_id) == 'super_admin':
            list = self.queryset.all().order_by('id')
        elif check_group_id(user_group_id) == 'company_admin':
            # 查公司用户
            user_list = User.objects.filter(company_id=self.request.user.company_id).values('id')
            list = self.queryset.filter(creator_user_id__in=user_list).order_by('id')
        elif check_group_id(user_group_id) == 'person':
            # 查个人
            list = self.queryset.filter(creator_user_id=self.request.user.id).order_by('id')

        elif check_group_id(user_group_id) == 'staff':
            # 查员工
            list = self.queryset.filter(creator_user_id=self.request.user.id).order_by('id')

        title = request.GET.get('title')
        types = request.GET.get('types')
        if title:
            list = list.filter(
                Q(title__icontains=title))
        if types:
            list = list.filter(
                Q(types=types))

        page = self.paginate_queryset(list)

        serializer = self.get_serializer(list, many=True)
        if page is not None:
            serializer = self.get_paginated_response(serializer.data)
            for item in serializer.data['results']:
                cover_image = Image.objects.filter(id=item['cover_image_id']).first()
                if len(item['label']) > 0:
                    labels = Label.objects.filter(id__in=item['label'].split(",")).values()
                else:
                    labels = []
                item['cover_image_url'] = settings.HTTP_MEDIA_URL + str(cover_image.image)
                item['labels'] = labels

                # 获取当前的skus_id
                if item['skus_id'] == '1':
                    platefroms = Platefrom.objects.filter(id__in=item['platefroms_id'].split(',')).values()
                    item['platefroms'] = platefroms
                else:
                    # 获取当前的skus_id
                    skus = Skus.objects.filter(id=item['skus_id']).first()
                    platefroms = Platefrom.objects.filter(id__in=skus.platefrom_ids.split(',')).values()
                    item['platefroms'] = platefroms

        return APIResponse(results=serializer.data)

    @action(methods=['get'], detail=False, url_path='all')
    def all_list(self, request, *args, **kwargs):
        # 查询普通用户
        queryset = self.get_queryset().filter(is_auth=1)
        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=serializer.data)

    @action(methods=['patch'], detail=False, url_path='process_all')
    def bulk_process(self, request, *args, **kwargs):
        if not self.request.data['data']:
            return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

        ids = self.request.data['ids']
        agree = self.request.data['data']['agree']
        if agree:
            disagree_reason = '审核通过'
        else:
            disagree_reason = self.request.data['data']['disagree_reason']
        if ids:
            ######################### author@ixiaofang===================
            # queryset = self.get_queryset().filter(id__in=ids)
            queryset = self.queryset.filter(id__in=ids)
            types_count = queryset.annotate(types_count=Count('types')).count()

            if queryset and types_count == 1:
                types = queryset.first().types
                if types == 'saves':
                    """保存-》待审核"""
                    # return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                    if agree:  # 提交
                        queryset.update(types='checking', disagree_reason=disagree_reason, reviewed_user=None)
                        medias_log_status = '提交成功'
                    else:  # 错误
                        return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                elif types == 'checking':
                    """待审核-》通过"""
                    if agree:  # 通过
                        # 批量插入 account_bind 表
                        account_bind_media_content_list = []

                        # 批量更新
                        # queryset_update_list = []
                        for item in queryset:
                            item.types = 'distribute'
                            item.save()

                            if item.skus_id != '1':

                                skus = Skus.objects.filter(id=item.skus_id).first()
                                platefroms = Platefrom.objects.filter(id__in=skus.platefrom_ids.split(',')).values()
                                for platefrom in platefroms:

                                    user = User.objects.filter(id=item.creator_user_id).first()

                                    if len(item.accounts_mobiles) > 1:
                                        if check_group_id(user.group_id) == 'person':
                                            account = UserAccountBind.objects.filter(user_id=item.creator_user_id,
                                                                                     plate_account__in=item.accounts_mobiles.split(
                                                                                         ',')).values()
                                        else:
                                            # 查公司
                                            account = UserAccountBind.objects.filter(company_id=user.company_id,
                                                                                     plate_account__in=item.accounts_mobiles.split(
                                                                                         ',')).values()
                                    else:
                                        if check_group_id(user.group_id) == 'person':
                                            account = UserAccountBind.objects.filter(user_id=item.creator_user_id,
                                                                                     platefrom_id=platefrom[
                                                                                         'id']).values()
                                        else:
                                            # 查公司
                                            account = UserAccountBind.objects.filter(company_id=user.company_id,
                                                                                     platefrom_id=platefrom[
                                                                                         'id']).values()
                                    if account is None:
                                        continue
                                    else:
                                        for account_item in account:
                                            account_bind_media_content = AccountBindMediaContent()
                                            account_bind_media_content.account = account_item['plate_account']
                                            account_bind_media_content.android_login_file = account_item[
                                                'app_account_upload']
                                            account_bind_media_content.priority = 1
                                            account_bind_media_content_list.append(account_bind_media_content)

                                            account_bind_media_content.status = 0
                                            account_bind_media_content.media_title = item.title
                                            account_bind_media_content.media_desc = item.desc
                                            account_bind_media_content.platform_name = platefrom['en_name']
                                            account_bind_media_content.url = item.media
                                            account_bind_media_content.media_content_in_platform_id = platefrom['id']
                                            account_bind_media_content.account_id = item.creator_user_id
                                            account_bind_media_content.media_content_id = item.id
                            else:
                                platefroms = Platefrom.objects.filter(id__in=item.platefroms_id.split(',')).values()
                                for platefrom in platefroms:

                                    user = User.objects.filter(id=item.creator_user_id).first()

                                    if len(item.accounts_mobiles) > 1:
                                        if check_group_id(user.group_id) == 'person':
                                            account = UserAccountBind.objects.filter(user_id=item.creator_user_id,
                                                                                     plate_account__in=item.accounts_mobiles.split(
                                                                                         ',')).values()
                                        else:
                                            # 查公司
                                            account = UserAccountBind.objects.filter(company_id=user.company_id,
                                                                                     plate_account__in=item.accounts_mobiles.split(
                                                                                         ',')).values()
                                    else:
                                        if check_group_id(user.group_id) == 'person':
                                            account = UserAccountBind.objects.filter(user_id=item.creator_user_id,
                                                                                     platefrom_id=platefrom[
                                                                                         'id']).values()
                                        else:
                                            # 查公司
                                            account = UserAccountBind.objects.filter(company_id=user.company_id,
                                                                                     platefrom_id=platefrom[
                                                                                         'id']).values()
                                    if account is None:
                                        continue
                                    else:
                                        account_bind_media_content = AccountBindMediaContent()
                                        account_bind_media_content.account = account.plate_account
                                        account_bind_media_content.android_login_file = account.app_account_upload
                                        account_bind_media_content.priority = 1
                                        account_bind_media_content_list.append(account_bind_media_content)

                                        account_bind_media_content.status = 0
                                        account_bind_media_content.media_title = item.title
                                        account_bind_media_content.media_desc = item.desc
                                        account_bind_media_content.platform_name = platefrom['en_name']
                                        account_bind_media_content.url = item.media
                                        account_bind_media_content.media_content_in_platform_id = platefrom['id']
                                        account_bind_media_content.account_id = item.creator_user_id
                                        account_bind_media_content.media_content_id = item.id

                        # 批量插入
                        AccountBindMediaContent.objects.bulk_create(account_bind_media_content_list)
                        # MediasLog.objects.create(media=item, user=self.request.user, status='审核通过')
                        return Response(status=response_status.HTTP_204_NO_CONTENT)
                    else:  # 驳回
                        queryset.update(types='no_pass', disagree_reason=disagree_reason)
                        medias_log_status = '审核退回'
                    print(agree, queryset)

                #######author@ixiaofang======
                elif types == 'pass':
                    """通过-》分发中"""
                    if agree:  # 通过
                        # queryset.update(types='distribute', disagree_reason=disagree_reason)
                        print(queryset)
                        medias_log_status = '审核通过'
                    else:  # 撤回
                        queryset.update(types='checking', disagree_reason=disagree_reason)
                        medias_log_status = '撤回'
                    # return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')
                    return Response(status=response_status.HTTP_204_NO_CONTENT)

                elif types == 'no_pass':
                    """未通过-》待审核"""
                    return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')
                    # if agree:  # 通过
                    #     queryset.update(types='checking', disagree_reason=disagree_reason, reviewed_user=None)
                    #     medias_log_status = '审核通过'
                    # else:  # 撤回
                    #     # queryset.update(types='checking', disagree_reason=disagree_reason)
                    #     return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                ###author@ixiaofang 通过设备连接状态====
                # elif types == 'distribute':
                #     """分发中-》通过"""
                #     if agree:  # 通过
                #         queryset.update(types='pass_distribute', disagree_reason=disagree_reason)
                #         medias_log_status = '分发通过'
                #     else:  # 撤回
                #         queryset.update(types='pass', disagree_reason=disagree_reason)
                #         medias_log_status = '分发撤回'
                #     return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                elif types == 'delete':
                    """回收站-》保存"""
                    if agree:  # 错误
                        return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')
                    else:  # 撤回
                        # queryset.update(types='saves', disagree_reason=disagree_reason)
                        return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                else:
                    return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')

                # obj_list = []
                # for media_data in queryset:
                #     obj_list.append(MediasLog(media=media_data, user=self.request.user, status=medias_log_status))
                # MediasLog.objects.bulk_create(obj_list)
                return Response(status=response_status.HTTP_204_NO_CONTENT)
        return Response(status=response_status.HTTP_400_BAD_REQUEST, data='数据错误')


class ImageViewSet(viewsets.ModelViewSet):
    """（素材库）图片"""
    queryset = Image.objects.filter(is_image=True).order_by('-update_time', 'title').values()
    serializer_class = ImageSerializer
    pagination_class = PageNumberPaginationUtil
    filterset_class = ImageFilter
    conditions = 'Image'

    # permissions = permissions.AllowAny
    # def get_permissions(self):
    #     """授权:通过菜单规则判断是否有增删改查权限（该用户是否有该菜单的增删改查等功能）"""
    #     print(permissions.IsAuthenticated())
    #     print(IsMenuPermission(self.conditions, self.action))
    #     return [permissions.IsAuthenticated(), IsMenuPermission(self.conditions, self.action)]

    # def get_queryset(self):
    #     """
    #     访问数据范围:通过访问权限判断哪些数据可被增删改查（个人数据、所在部门数据、公司数据等）
    #     """
    #     queryset = GetQueryset(self.queryset, self.request.user,[], self.action) \
    #         .get_user_permission_data().get_queryset_data()
    #
    #     return queryset

    def list(self, req, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        # name = request.GET.get('name')
        user_group_id = req.user.group_id
        user_id = req.user.id
        image_label_id = req.GET.get('image_label_id')
        # if name:
        #     queryset = queryset.filter(
        #         Q(name__icontains=name))
        if image_label_id:
            queryset = queryset.filter(
                Q(image_label_id=image_label_id))
        if image_label_id == 2:
            if check_group_id(user_group_id) == 'person' or check_group_id(user_group_id) == 'staff':
                queryset = queryset.filter(
                    Q(creator_user_id=user_id))
            if check_group_id(user_group_id) == 'company_admin':
                # 查公司用户
                user_list = User.objects.filter(company_id=self.request.user.company_id).values('id')
                queryset = queryset.filter(
                    Q(creator_user_id__in=user_list))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        image = list(queryset.values())
        if page is not None:
            serializer = self.get_serializer(page, many=True)

        for data_item, image_item in zip(serializer.data, image):
            image_item['image'] = settings.HTTP_MEDIA_URL + str(image_item['image'])
            data_item.update(image_item)
        return VueAPIResponse(self, queryset, data=self.get_paginated_response(serializer.data).data)

    # 识别上传文件类型
    def create(self, request, *args, **kwargs):
        # 获取上传的文件类型
        file_type = request.FILES['image'].content_type
        # print("上传的文件",file_type)
        # 根据文件类型更新is_image字段的值
        if file_type.startswith('image/'):
            request.data['is_image'] = True
        elif file_type.startswith('video/'):
            request.data['is_image'] = False

        return super().create(request, *args, **kwargs)


class VideoViewSet(viewsets.ModelViewSet):
    """（素材库）视频"""
    # queryset = Image.objects.all().order_by('-update_time', 'title')
    queryset = Image.objects.filter(is_image='0').order_by('-update_time', 'title')
    serializer_class = VideoSerializer
    pagination_class = PageNumberPaginationUtil
    filterset_class = ImageFilter
    conditions = 'Image'

    # def get_permissions(self):
    #     """授权:通过菜单规则判断是否有增删改查权限（该用户是否有该菜单的增删改查等功能）"""
    #     return [permissions.IsAuthenticated(), IsMenuPermission(self.conditions, self.action)]

    # def get_queryset(self):
    #     """
    #     访问数据范围:通过访问权限判断哪些数据可被增删改查（个人数据、所在部门数据、公司数据等）
    #     """
    #     queryset = GetQueryset(self.queryset, self.request.user, self.conditions, self.action) \
    #         .get_user_permission_data().get_queryset_data()
    #
    #     return queryset

    def list(self, req, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)

        # name = request.GET.get('name')
        user_group_id = req.user.group_id
        user_id = req.user.id
        image_label_id = req.GET.get('image_label_id')
        # if name:
        #     queryset = queryset.filter(
        #         Q(name__icontains=name))
        if image_label_id:
            queryset = queryset.filter(
                Q(image_label_id=image_label_id))
        if image_label_id == 2:
            if check_group_id(user_group_id) == 'person' or check_group_id(user_group_id) == 'staff':
                queryset = queryset.filter(
                    Q(creator_user_id=user_id))
            if check_group_id(user_group_id) == 'company_admin':
                # 查公司用户
                user_list = User.objects.filter(company_id=self.request.user.company_id).values('id')
                queryset = queryset.filter(
                    Q(creator_user_id__in=user_list))

        # image = list(Image.objects.filter(is_image=False).values())
        if page is not None:
            serializer = self.get_serializer(page, many=True)

        for item in serializer.data:
            temp_image_url = str(item['image']).replace("http://127.0.0.1:8000/media/", settings.HTTP_MEDIA_URL)
            item['image'] = temp_image_url
            item.update(item)

        # for data_item, image_item in zip(serializer.data, image):
        #     image_item['image'] = settings.HTTP_MEDIA_URL + str(image_item['image'])
        #     data_item.update(image_item)
        return VueAPIResponse(self, queryset, data=self.get_paginated_response(serializer.data).data)

    # 识别上传文件类型
    def create(self, request, *args, **kwargs):
        # 获取上传的文件类型
        file_type = request.FILES['image'].content_type
        # print("上传的文件",file_type)
        # 根据文件类型更新is_image字段的值
        if file_type.startswith('image/'):
            request.data['is_image'] = True
        elif file_type.startswith('video/'):
            request.data['is_image'] = False

        return super().create(request, *args, **kwargs)


class ContentTypeViewSet(viewsets.ModelViewSet):
    """通用标签类型"""
    queryset = ContentType.objects.all()
    serializer_class = ContentTypeSerializer
    # permissions = permissions.IsAdminUser
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)


class ContentLabelViewSet(viewsets.ModelViewSet):
    """通用内容标签类型"""
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    # permissions = permissions.IsAdminUser
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        search = request.GET.get('search')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)

    @action(methods=['get'], detail=False, url_path='all')
    def all_list(self, request, *args, **kwargs):
        # 查询全部
        queryset = self.get_queryset().filter()
        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=serializer.data)


# 设备按照优先级
@method_decorator(csrf_exempt, name='dispatch')
@permission_classes([])
class MediaDeviceTask(viewsets.ModelViewSet):
    """通用内容标签类型"""
    queryset = AccountBindMediaContent.objects.filter(status=0).order_by('priority')

    @action(methods=['get'], detail=False, url_path='device_task')
    def all_list(self, request, *args, **kwargs):
        # 查询全部
        queryset = self.get_queryset().filter()

        if len(queryset) > 0:
            for i in queryset:
                if i.platform_name == 'bilibili':
                    # 推送登录文件
                    task_login = PushAccountTask(bilibili_file_pkg, f'media/app/', f'{i.account}_{i.platform_name}')

                    # client.set_task(task_login)  # 设置任务
                    # 需要将登陆任务和发布任务绑定在一起（绑定在同一台设备）
                    # client.run_current_task()  # 开始运行任务

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = BilibiliPublishVideoTask(priority=1, title=i.media_title, content=i.media_desc,
                                                            video=url,
                                                            download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    # task = CombinedSequentialTask(task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

                # 快手
                if i.platform_name == 'kuaishou':
                    # 推送登录文件
                    task_login = PushAccountTask(kuaishou_file_pkg, f'media/app/', f'{i.account}_{i.platform_name}')

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = KuaishouPublishVideoTask(priority=1, title=i.media_title, content=i.media_desc,
                                                            video=url,
                                                            download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

                # 小红书
                if i.platform_name == 'xiaohongshu':
                    # 推送登录文件
                    task_login = PushAccountTask(xhs_file_pkg, f'media/app/', f'{i.account}_{i.platform_name}')

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = XhsPublishVideoTask(priority=1, title=i.media_title, content=i.media_desc,
                                                       video=url,
                                                       download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

                # 抖音火山
                if i.platform_name == 'douyinhuoshan':
                    # 推送登录文件
                    task_login = PushAccountTask(douyinhuoshan_file_pkg, f'media/app/',
                                                 f'{i.account}_{i.platform_name}')

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = DouyinhuoshanPublishVideoTask(priority=1, title=i.media_title, content=i.media_desc,
                                                                 video=url, download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

                # 微博
                if i.platform_name == 'weibo':
                    # 推送登录文件
                    task_login = PushAccountTask(weibo_file_pkg, f'media/app/',
                                                 f'{i.account}_{i.platform_name}')

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = WeiboPublishVideoTask(priority=1, title=i.media_title,
                                                         content=i.media_desc,
                                                         video=url, download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

                # 微博
                if i.platform_name == 'toutiao':
                    # 推送登录文件
                    task_login = PushAccountTask(toutiao_file_pkg, f'media/app/',
                                                 f'{i.account}_{i.platform_name}')

                    url = i.url + "?rand=" + str(time.time())

                    # 编写回调函数
                    def device_task_success(e_cli, e_task):
                        # 发布成功
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=3)

                        # 查看所有账户都发布成功
                        find = AccountBindMediaContent.objects.filter(media_content_id=i.media_content_id).filter(
                            status=0).first()
                        if not find:
                            MediaContent.objects.filter(id=i.media_content_id).update(types='pass_distribute')

                        # 扣掉余额
                        media_content = MediaContent.objects.filter(id=i.media_content_id).first()
                        SkusUser.objects.filter(user_id=media_content.creator_user_id,
                                                skus_id=media_content.skus_id).update(
                            balance_times=F('balance_times') - 1)
                        pass

                    def device_task_error(e_cli, e_task, e_exception):
                        # 发布失败
                        AccountBindMediaContent.objects.filter(id=i.id).update(status=4)
                        return False

                    task_publish = ToutiaoPublishVideoTask(priority=1, title=i.media_title,
                                                         content=i.media_desc,
                                                         video=url, download_timeout=86400)

                    # 添加任务
                    # 两个任务绑定
                    task = CombinedSequentialTask(task_login, task_publish)
                    task.set_handler(device_task_error)
                    task.set_callback(device_task_success)
                    manager.push_task(task)

                    # 设置状态
                    AccountBindMediaContent.objects.filter(id=i.id).update(status=1)

        return APIResponse(results=[])
